﻿using EasyShop.GoodsService.App.Interface;
using EasyShop.GoodsService.Response;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;

namespace EasyShop.GoodsService.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class GoodsController : ControllerBase
    {
        private readonly IGoodsApp _goodsApp;
        private readonly IDistributedCache _cache;
        public GoodsController(IGoodsApp goodsApp,IDistributedCache cache)
        {
            _goodsApp = goodsApp;
            _cache = cache;
        }
        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Response<List<GoodsListView>> GetList()
        {
            const string cacheKey = "goods_list";
            var result = new Response<List<GoodsListView>>();
            try
            {
                //查询redis
                var goodsListJson = _cache.GetString(cacheKey);
                if (goodsListJson == null)
                {
                    //redis不存在，则查询库,之后把值放入redis
                    result.Result = _goodsApp.GetList();
                    var json = JsonConvert.SerializeObject(result.Result);
                    _cache.SetString(cacheKey, json);
                }
                else
                {
                    var goodsList = JsonConvert.DeserializeObject<List<GoodsListView>>(goodsListJson);
                    result.Result = goodsList;
                }
                
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return result;
        }
    }
}
